package cn.ctvonline.android.kaopu.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.ctvonline.android.kaopu.R;
import cn.ctvonline.android.kaopu.activity.FeatureDetailActivity;
import cn.ctvonline.android.kaopu.base.IncomingHandler;
import cn.ctvonline.android.kaopu.base.MessageHandleListener;
import cn.ctvonline.android.kaopu.constant.Constant;
import cn.ctvonline.android.kaopu.entity.ExpandEntry;
import cn.ctvonline.android.kaopu.fragment.adapter.FeatureRecyclerViewAdapter;
import cn.ctvonline.android.kaopu.support.AmapLocationManager;
import cn.ctvonline.android.kaopu.support.AmapSearchServer;
import cn.ctvonline.android.kaopu.widget.layout.ExpandLayout;
import cn.ctvonline.android.kaopu.widget.layout.SelectedLayout;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class FeatureFragment extends LazyBaseFragment {
    static final String TAG = FeatureFragment.class + "";
    private OnListFragmentInteractionListener mListener;
    private IncomingHandler handler;
    private List<PoiItem> itemList = new ArrayList<>();
    private AmapSearchServer poiSearch;
    private String keyword = "美食";
    private FeatureRecyclerViewAdapter mFeatureAdapter;
    private AMapLocation leastLocation;
    private int searchRadiusMeters = 10 * 1000;
    private LinearLayoutManager linearLayoutManager;
    private View rootView;
    private ImageView refershLocIv;
    private TextView lastLocTv;
    @Bind(R.id.feature_recycle_view)
    RecyclerView recyclerView;
    @Bind(R.id.feature_condition_sort_tv)
    TextView condSortSp;
    @Bind(R.id.feature_condition_type_tv)
    TextView condTypeSp;
    @Bind(R.id.feature_condition_zone_tv)
    TextView condZoneSp;
    @Bind(R.id.feature_condition_sort_sl)
    SelectedLayout condSortSl;
    @Bind(R.id.feature_condition_type_sl)
    SelectedLayout condTypeSl;
    @Bind(R.id.feature_condition_zone_sl)
    SelectedLayout condZoneSl;
    @Bind(R.id.feature_expand_lay)
    ExpandLayout expandLayout;
    @Bind(R.id.feature_back_top_iv)
    ImageView backTopIv;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.i(TAG, "this is featureFragment onCreateView ");
        super.onCreateView(inflater, container, savedInstanceState);
        rootView = inflater.inflate(R.layout.fragment_feature, container, false);
        mListener = new OnListFragmentInteractionListener() {
            @Override
            public void onListFragmentInteraction(PoiItem item, View view) {
                Intent intent = new Intent(activity, FeatureDetailActivity.class);
                activity.startActivity(intent);
            }
        };
        initViews();
        initHandler();
        initPoiSearch();
        initCondSelector();
        return rootView;
    }

    @OnClick({R.id.feature_condition_sort_sl, R.id.feature_condition_type_sl, R.id.feature_condition_zone_sl})
    public void onSelectLayoutClicked(View view) {
        switch (view.getId()) {
            case R.id.feature_condition_sort_sl: {
                condSortSl.setSelected(!condSortSl.isSelected());
                condTypeSl.setSelected(false);
                condZoneSl.setSelected(false);
            }
            break;
            case R.id.feature_condition_type_sl: {
                condSortSl.setSelected(false);
                condTypeSl.setSelected(!condTypeSl.isSelected());
                condZoneSl.setSelected(false);
            }
            break;
            case R.id.feature_condition_zone_sl: {
                condSortSl.setSelected(false);
                condTypeSl.setSelected(false);
                condZoneSl.setSelected(!condZoneSl.isSelected());
            }
            break;
        }
        showSelectWindow((SelectedLayout) view);
    }

    private void initCondSelector() {
        Constant.initExpand();
        final List<ExpandEntry> leftList = Constant.expandList;
        final List<ExpandEntry> rightList = new ArrayList<>();
        expandLayout.setOutTouchable(true);
        expandLayout.setLeftValues(leftList);
        expandLayout.setBackground(new ColorDrawable(getResources().getColor(R.color.half_transluent)));
        expandLayout.setOnExpandVisiableChangeListener(new ExpandLayout.OnExpandVisiableChangeListener() {
            @Override
            public void onExpandShow() {

            }

            @Override
            public void onExpandHide() {
                condZoneSp.setSelected(false);
                condSortSl.setSelected(false);
                condTypeSl.setSelected(false);
            }
        });
        expandLayout.setOnExpandItemClickListener(new ExpandLayout.OnExpandItemClickListener() {
            @Override
            public void onLeftItemClicked(int position) {
                rightList.clear();
                ExpandEntry entry = leftList.get(position);
                if (entry.isHasMore()) {
                    rightList.addAll(entry.getMoreList());
                } else {
                    condTypeSp.setText(leftList.get(position).getValue());
                    condTypeSp.setTag(leftList.get(position).getValue());
                    expandLayout.hide();
                }
                expandLayout.setRightValues(rightList);
            }

            @Override
            public void onRightItemClicked(int leftPosition, int rightPosition) {
                condTypeSp.setText(rightList.get(rightPosition).getValue());
                condTypeSp.setTag(leftList.get(leftPosition).getValue());
                expandLayout.hide();
            }
        });
    }

    public void showSelectWindow(SelectedLayout rootView) {
        expandLayout.toggle();
    }

    private boolean loadingData = false;

    private void initViews() {
        ButterKnife.bind(this, rootView);
        RelativeLayout headView = (RelativeLayout) LayoutInflater.from(activity).inflate(R.layout.recycle_head_view, null, false);
        refershLocIv = (ImageView) headView.findViewById(R.id.feature_refersh_location_iv);
        lastLocTv = (TextView) headView.findViewById(R.id.feature_location_tv);
        linearLayoutManager = new LinearLayoutManager(activity);
        recyclerView.setLayoutManager(linearLayoutManager);
        mFeatureAdapter = new FeatureRecyclerViewAdapter(itemList, mListener);
        mFeatureAdapter.setHeadView(headView);
        recyclerView.setAdapter(mFeatureAdapter);
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            int visiableCount = 0;
            int firstVisiablePosi = 0;
            int totalCount = 0;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                totalCount = linearLayoutManager.getItemCount();
                visiableCount = linearLayoutManager.getChildCount();
                firstVisiablePosi = linearLayoutManager.findFirstVisibleItemPosition();
                if (firstVisiablePosi == 0) {
                    backTopIv.setVisibility(View.GONE);
                } else {
                    if (linearLayoutManager.findFirstCompletelyVisibleItemPosition() > 0) {
                        backTopIv.setVisibility(View.VISIBLE);
                    }
                }
                if (firstVisiablePosi > 0 && (visiableCount + firstVisiablePosi >= totalCount) && !loadingData) {
                    //使底部加载view可见
                    loadDataStyle = LOAD_DATA_MORE;
                    loadMore();
                }
            }
        });
        refershLocIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Animation rotation = AnimationUtils.loadAnimation(activity, R.anim.rotation);
                refershLocIv.startAnimation(rotation);
                requestLocation();
                v.setEnabled(false);
            }
        });
        backTopIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerView.scrollToPosition(0);
            }
        });
    }

    private void initPoiSearch() {
        poiSearch = new AmapSearchServer(activity);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                if (poiResult != null && poiResult.getPois() != null) {
                    loadingData = false;
                    List<PoiItem> list = poiResult.getPois();
                    itemList.addAll(list);
                    mFeatureAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void initHandler() {
        handler = getHandler();
        handler.setOnMessageHandleListener(new MessageHandleListener() {
            @Override
            public void onHandlerMessage(Message msg) {
                switch (msg.what) {
                    case GET_LOCATION_START: {
                    }
                    break;
                    case GET_LOCATION_FINISHED: {
                        refershLocIv.clearAnimation();
                        refershLocIv.setEnabled(true);
                        Bundle bundle = msg.getData();
                        leastLocation = bundle.getParcelable("aMapLocation");
                        String address = leastLocation.getAddress();
                        lastLocTv.setText(address);
                        if (loadDataStyle == LOAD_DATA_REFERSH) {
                            itemList.clear();
                        }
                        lazyLoadData();
                    }
                    break;
                    case GET_LOCATION_FAILED: {
                        refershLocIv.clearAnimation();
                        refershLocIv.setEnabled(true);
                        if (leastLocation == null) {
                            lastLocTv.setText("获取位置失败");
                        } else {
                            lazyLoadData();
                        }
                    }
                    break;
                }
            }
        });
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnListFragmentInteractionListener {
        void onListFragmentInteraction(PoiItem item, View view);
    }

    static final int GET_LOCATION_START = 0x01;
    static final int GET_LOCATION_FINISHED = 0x02;
    static final int GET_LOCATION_FAILED = 0x03;

    @Override
    protected synchronized void lazyLoadData() {
        loadDataStyle = LOAD_DATA_REFERSH;
        if (leastLocation != null) {
            LatLonPoint centerPoint = new LatLonPoint(leastLocation.getLatitude(), leastLocation.getLongitude());
            poiSearch.initSearchParam(keyword, "", leastLocation.getCityCode(), centerPoint, searchRadiusMeters);
            poiSearch.poiSearch();
            loadingData = true;
        }
    }

    private int pageNum = 0;
    static final int LOAD_DATA_REFERSH = 0x01;
    static final int LOAD_DATA_MORE = 0x02;
    int loadDataStyle = LOAD_DATA_REFERSH;

    private synchronized void loadMore() {
        loadDataStyle = LOAD_DATA_MORE;
        pageNum += 1;
        poiSearch.setCurrentPage(pageNum);
        poiSearch.poiSearch();
        loadingData = true;
    }

    private void requestLocation() {
        handler.sendEmptyMessage(GET_LOCATION_START);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //加载缓存的数据
                AMapLocation lastLocation = AmapLocationManager.getInstance().mLocationClient.getLastKnownLocation();
                int locTimes = 0;
                try {
                    while (lastLocation == null && locTimes < 5) {
                        lastLocation = AmapLocationManager.getInstance().mLocationClient.getLastKnownLocation();
                        Thread.sleep(1000);
                        locTimes++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Message msg = Message.obtain();
                if (lastLocation != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("aMapLocation", lastLocation);
                    msg.setData(bundle);
                    msg.what = GET_LOCATION_FINISHED;
                } else {
                    msg.what = GET_LOCATION_FAILED;
                }
                handler.sendMessage(msg);
                AmapLocationManager.getInstance().stopLocation();
            }
        }).start();
    }

    class CondAdapter extends BaseAdapter {
        private Context context;
        private List<String> list;

        public CondAdapter(Context context, List<String> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Object getItem(int position) {
            return list == null ? null : list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.dialog_simple_value_item, parent, false);
                holder.itemTv = (TextView) convertView.findViewById(R.id.dialog_simple_item_tv);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.itemTv.setText(list.get(position));
            convertView.setTag(holder);
            return convertView;
        }

        class ViewHolder {
            TextView itemTv;
        }
    }
}
